package com.sp2.dev.test.sort;

import org.junit.Test;

/**
 * Created by IntelliJ IDEA.
 * User: zhimingli
 * Date: 14-2-12
 * Time: 下午2:18
 * To change this template use File | Settings | File Templates.
 */
public class BuddleSortArray {

    private static double arr[] = new double[100];

    static {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Math.random();
        }
    }

    public static void main(String[] args) {
        arr = sort(arr);
         for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }


    //冒泡（Bubble）排序
    //效率 O（n²）,适用于排序小列表。
    @Test
    public void bubbleSortArray() {
        double arr2[] = new double[100];
        for (int i = 0; i < arr2.length; i++) {
            arr2[i] = Math.random();
        }
        for (int i = 1; i < arr2.length; i++) {
            for (int j = 0; i < arr2.length - j; j++) {
                if (arr2[j] > arr2[j + 1]) {//swap
                    double temp = arr2[j];
                    arr2[j] = arr2[j + 1];
                    arr2[j + 1] = temp;
                }
            }
        }

        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }
    }


    public static double[] sort(double[] a) {
        //将传递的数组参数a克隆对象，不改变a数组的值
        double[] array = a.clone();
        //总共进行length -1 趟排序
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j + 1] <= array[j]) {
                    double temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        return array;
    }


}
